import json
import socket

import jmespath
import pytest

from commons.common_tools import read_yml, extract_ip_from_url, write_to_json_file
from commons.user_login import UserLogin

login_info = read_yml("config.yml")
base_host = login_info["test_url"]
product = login_info["product"]
username = login_info["username"]
password = login_info["password"]
port = login_info["port"]


def get_mate_data_value(login_session):
    params = {
        'page': '1',
        'rows': '100',
        'sidx': '',
        'sord': '',
        'isbase': '',
        'fieldtype': '',
        'enumtype': '2',
        'isfilter': '',
        'isdisplay': '',
        'isenrich': '',
        'isorder': '',
        'ismerge': '',
        'name': '',
        'metadataType': 'metadata_log',
        'deptid': ''
    }
    response = login_session.get(f"{base_host}/{product}/api/v2/logfield/metadata/searchList", params=params,
                                 verify=False)

    data_json = {}
    data_enname_list = jmespath.search("data.data[].enname", response.json())
    for enname in data_enname_list:
        data = f'fieldenname={enname}&enumtype=2&superiorid='
        response = login_session.post(f'{base_host}/{product}/api/v2/metadata/dict/getDictListByEnname',
            headers={'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
            data=str(data).encode("utf-8"),
            verify=False)
        # print(response.text)
        key_value_list = jmespath.search("data[0].dictChild[].[dictcode,dictname]", response.json())
        data_json[enname] = {}
        if key_value_list:
            for item in key_value_list:
                data_json[enname][item[0]] = item[1]
    # 处理日志源类型字段
    params = {
        'page': '1',
        'rows': '300',
        'parentId': '',
        'typecode': '',
        'sidx': '',
        'sord': ''
    }

    response = login_session.get(
        f'{base_host}/{product}/api/v2/dept/classification/list',
        params=params,
        verify=False)
    # print('我是打印出来的日志源数据',response.text)
    csrclogtype_dict = {}
    for item in response.json().get("data").get("data"):
        csrclogtype_dict[item["typecode"]] = item["typename"]
    data_json["csrclogtype"]=csrclogtype_dict
    print(json.dumps(data_json, ensure_ascii=False))
    write_to_json_file("data/data_value.json", data_json)
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Referer': f'{base_host}/{product}/system/service/enterauths'
    }
    data = {
        'csrfcheck': 'true',
        'outAPI': 'false',
        'outAPIRate': '20000',
        'origin': '',
        '___validator_form_idx___': '0',
    }

    response = login_session.post(f'{base_host}/{product}/system/service/saveuser',
        headers=headers,
        data=data,
        verify=False)
    print(response.text)



@pytest.fixture(scope="session", autouse=True)
def current_session():
    # 使用环境信息
    # 使用用户名密码信息
    # 使用登录接口
    host = f"{base_host}/{product}"
    user = UserLogin(host, username, password)
    session, token = user.user_login()
    get_mate_data_value(session)

    yield session


# @pytest.fixture(scope="session", autouse=True)
# def udp_socket():
#


@pytest.fixture(scope="session", autouse=True)
def host():
    host = f"{base_host}/{product}"
    yield host


@pytest.fixture(scope="session", autouse=True)
def target_ip():
    target_ip = extract_ip_from_url(base_host)
    yield target_ip


@pytest.fixture(scope="session", autouse=True)
def target_port():
    target_port = f"{port}"
    yield target_port
